import { _decorator, Node, Rect, UITransform } from 'cc';

export class BoxMath {

    /**
     * 判断两个Node是否相交
     * @param node1 第一个节点
     * @param node2 第二个节点
     * @returns 如果两个节点相交返回true，否则返回false
     */
    static isIntersecting(node1: Node, node2: Node): boolean {
        if (!node1 || !node2) {
            return false;
        }

        // 获取两个节点的UITransform组件
        const transform1 = node1.getComponent(UITransform);
        const transform2 = node2.getComponent(UITransform);

        if (!transform1 || !transform2) {
            return false;
        }

        // 获取节点的世界坐标
        const worldPos1 = node1.getWorldPosition();
        const worldPos2 = node2.getWorldPosition();

        // 获取节点的尺寸
        const size1 = transform1.contentSize;
        const size2 = transform2.contentSize;

        // 获取锚点
        const anchor1 = transform1.anchorPoint;
        const anchor2 = transform2.anchorPoint;

        // 计算包围盒的边界
        const left1 = worldPos1.x - size1.width * anchor1.x;
        const right1 = worldPos1.x + size1.width * (1 - anchor1.x);
        const top1 = worldPos1.y + size1.height * (1 - anchor1.y);
        const bottom1 = worldPos1.y - size1.height * anchor1.y;

        const left2 = worldPos2.x - size2.width * anchor2.x;
        const right2 = worldPos2.x + size2.width * (1 - anchor2.x);
        const top2 = worldPos2.y + size2.height * (1 - anchor2.y);
        const bottom2 = worldPos2.y - size2.height * anchor2.y;

        // AABB碰撞检测
        return !(right1 < left2 || left1 > right2 || top1 < bottom2 || bottom1 > top2);
    }

    /**
     * 获取节点的世界包围盒
     * @param node 节点
     * @returns 返回包围盒的Rect对象，如果节点无效则返回null
     */
    static getWorldBoundingBox(node: Node): Rect | null {
        if (!node) {
            return null;
        }

        const transform = node.getComponent(UITransform);
        if (!transform) {
            return null;
        }

        const worldPos = node.getWorldPosition();
        const size = transform.contentSize;
        const anchor = transform.anchorPoint;

        const left = worldPos.x - size.width * anchor.x;
        const bottom = worldPos.y - size.height * anchor.y;

        return new Rect(left, bottom, size.width, size.height);
    }
}